package com.happy.people.cofig;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.sql.core.ClasspathLoader;
import org.beetl.sql.core.DefaultNameConversion;
import org.beetl.sql.core.Interceptor;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.ext.spring4.BeetlSqlDataSource;
import org.beetl.sql.ext.spring4.SqlManagerFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author : Yan
 * @Description : beetlsql config
 */
@Configuration
@Profile(value = "db")
@Slf4j
public class BeetlSqlConfig {

    @Bean(initMethod = "init",name = "beetlConfig")
    public BeetlGroupUtilConfiguration getBeetlGroupUtilConfigurable(){
        BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
        ClasspathResourceLoader classpathResourceLoader = new ClasspathResourceLoader();
        beetlGroupUtilConfiguration.setResourceLoader(classpathResourceLoader);
        // 读取配置文件信息
        return beetlGroupUtilConfiguration;
    }

    @Bean(name="datasource")
    public DataSource datasource(Environment env) {
        String url = env.getProperty("spring.datasource.url");
        String userName = env.getProperty("spring.datasource.userName");
        String passWord = env.getProperty("spring.datasource.passWord");
        String driverClassName = env.getProperty("spring.datasource.driver-class-name");
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl(url);
        ds.setUsername(userName);
        ds.setPassword(passWord);
        ds.setDriverClassName(driverClassName);
        return ds;
    }

    //开启事务
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("datasource") DataSource datasource) {
        DataSourceTransactionManager dsm = new DataSourceTransactionManager();
        dsm.setDataSource(datasource);
        return dsm;
    }

}
